<template>
    <view class="index home-bg">
        <u-sticky offset-top="0" h5-nav-height="0" bg-color="transparent" :enable="enable">
            <u-navbar
				title="七仔生活"
				titleColor="#FFF"
                :border-bottom="false"
                :is-fixed="false"
                custom-class="home-bg" 
                :background="navBackground"
                :title-color="'#fff'"
                :is-back="false"
            >
			<view class="u-nav-slot row" slot="left" @tap="handleCityChange">
				<image class="location-img" :src="`${imgPrefix}/images/xcxweb/index/location.png`"></image>
				<text> {{cityName || '未知'}} </text>
			</view>
            </u-navbar>
        </u-sticky>
		<!-- 搜索 -->
		<view class="search-wrapper row-end">
			<view class="search-box" @tap="goPage('/pages/goods_search/goods_search')">
				<image :src="`${imgPrefix}/images/xcxweb/index/search.png`" />
			</view>
		</view>
		
        <view class="contain">
            <view class="main">
				<!-- 菜单导航 -->
				<view class="menu-box row-center">
					<view class="menu-item column-center flex1" v-for="(item, index) in menuList" :key="item.id" @tap="handleMenu(item, index)">
						<image :src="item.image" />
						{{item.name}}
					</view>
				</view>
				<!-- 邀请 -->
				<button :open-type="inviteOpenType" class="column column-center" hover-class="none" @tap="handleInvite">
					<view class="invite-box">
						<image :src="`${imgPrefix}/images/xcxweb/index/invite.png`"></image>
						<view class="invite-txt-box">
							<view class="txt1">每邀请<text>1</text>人购买卡包</view>
							<view class="txt2">赠送<text>{{copywritingObj.second_give_bamboo || 0}}</text>根玉竹</view>
						</view>
					</view>
				</button>
				<!-- 排行榜、秒杀 -->
				<view class="seckill-box">
					<view class="left">
						<view class="hd row-between" @tap="goPage('/bundle/pages/bamboo_rank/bamboo_rank')">
							玉竹兑换排行榜
							<image  :src="`${imgPrefix}/images/xcxweb/index/rank_right_arrow.png`"></image>
						</view>
						<view class="bd">
							<template v-if="bambooRankList.length > 0">
								<view class="goods-item" v-for="(item,index) in bambooRankList.slice(0,2)" :key="item.id" @tap="toDetails(item.id)"> 
									<image :src="item.image" class="goods-img"></image>
									<image :src="`${imgPrefix}/images/xcxweb/index/rank${index+1}.png`" class="rank-img"></image>
									<view class="exchange-btn">{{item.bamboo_range}}玉竹兑换</view>
									<view class="desc-box">{{item.name}}</view>
								</view>
							</template>
							<view class="data-null column-center" v-else>
							    <image class="img-null" :src="`${imgPrefix}/images/xcxweb/goods_null.png`"></image>
							    <view class="muted nr">暂无商品～</view>
							</view>
							<!-- <loading-footer :status="bambooRankStatus" slotEmpty>
							    <view class="data-null column-center" slot="empty">
							        <image class="img-null" :src="`${imgPrefix}/images/xcxweb/goods_null.png`"></image>
							        <view class="muted nr">暂无商品～</view>
							    </view>
							</loading-footer> -->
						</view>
					</view>
					<view class="right">
						<view class="hd row-between">
							秒杀倒计时
							<view class="countdown-box row" v-if="seckillGoods.length > 0">
								<u-count-down
								    :timestamp="remainTime"
								    separator-color="#3D3D3D"
								    color="#FFF"
								    :separator-size="24"
								    :font-size="24"
								    bg-color="#FF7272"
									border-color="#FF7272"
								></u-count-down>
							</view>
						</view>
						<template v-if="seckillGoods.length > 0">
							<view class="bd" v-for="(item,index) in seckillGoods.slice(0,1)" :key="index"  @tap="toDetails(item.id)">
									<image :src="item.image" class="goods-img" />
									<view class="info-box row-between">
										<view class="title">{{item. name}}</view>
										<view class="able-btn">可抢</view>
									</view>
									<view class="price-box row">
										<view class="price">¥{{item.seckill_price}}</view>
										<view class="unit-box">仅需{{item.bamboo_num}}根玉竹</view>
									</view>
							</view>
						</template>
						<view class="data-null column-center" v-else>
						    <image class="img-null" :src="`${imgPrefix}/images/xcxweb/goods_null.png`"></image>
						    <view class="muted nr">暂无商品～</view>
						</view>
						<!-- <loading-footer :status="seckillStatus" slotEmpty>
						    <view class="data-null column-center" slot="empty">
						        <image class="img-null" :src="`${imgPrefix}/images/xcxweb/goods_null.png`"></image>
						        <view class="muted nr">暂无商品～</view>
						    </view>
						</loading-footer> -->
					</view>
				</view>
				
				<!-- 商品 -->
				<view class="show-goods-box">
					<tabs :config="tabsConfig" :active="tabActive" @change="onTabChange">
						<tab v-for="(item, index) in tabList" :key="item.type" :title="item.name">
							<view class="show-goods-list">
								<view class="show-goods-item" v-for="(goodsItem, goodsIndex) in goodsList" :key="goodsIndex" @tap="toDetails(goodsItem.id)">
									<view class="imgs-box">
										<image :src="goodsItem.yuzhu_image"  />
										<!-- <image :src="goodsItem.image"  /> -->
										<view class="distance-box row-center">
											<u-icon name="map" color="#FFF" size="24" :custom-style="{marginRight: '6rpx'}"></u-icon>
											{{goodsItem.distance_km}}
										</view>
									</view>
									<view class="content-box">
										<view class="title">{{goodsItem.name}} | {{goodsItem.store_name}}</view>
										<view class="intro">【{{goodsItem.store_name}}】{{goodsItem.remark}}</view>
										<view class="num-box row">
											门市价
											<view class="price-box"><text class="unit">¥</text>{{goodsItem.market_price}}</view>
											<view class="subsidy-box">可用补贴 {{goodsItem.big_subsidy}}</view>
										</view>
										<!-- 玉竹兑换 -->
										<view class="exchange-box" v-if="tabActive == 0">
											<view>{{goodsItem.min_jade_bamboo_sum}}玉竹</view>
											兑换
										</view>
										<!-- 百亿补贴 -->
										<view class="gain-box"  v-if="tabActive == 1">
											得 {{goodsItem.first_ratio}}
										</view>
									</view>
								</view>
							</view>
							<loading-footer :status="goodsStatus" slotEmpty>
									<view class="data-null column-center" slot="empty">
									    <image class="img-null" :src="`${imgPrefix}/images/xcxweb/goods_null.png`"></image>
									    <view class="muted nr">暂无商品～</view>
									</view>
							</loading-footer>
						</tab>
					</tabs>
				</view>
            </view>
        </view>
	   
        <!-- #ifdef APP-PLUS -->
        <lyg-popup
            v-if="appConfig.app_agreement"
            title="用户使用及隐私保护政策提示"
            protocolPath="/bundle/pages/server_explan/server_explan?type=0"
            policyPath="/bundle/pages/server_explan/server_explan?type=1"
            policyStorageKey="has_read_privacy"
        >
        </lyg-popup>
        <!-- #endif -->
		
		<share-popup v-model="showShareBtn"
			:share-id="id" 
			pagePath="pages/goods_details/goods_details" 
			:type="1" 
			:config="{
				avatar: userInfo.avatar,
				nickname: userInfo.nickname,
				name: (shareInfo && shareInfo.mnp_share_title) || '',
				path: 'pages/index/index?invite_code=' + this.inviteCode,
				image: shareInfo.mnp_share_image
		}">
		</share-popup>
		
        <!-- #ifdef MP-WEIXIN -->
        <!-- 用户隐私协议弹框 -->
        <privacy-popup v-model="showPrivacyPopup"></privacy-popup>
        <!-- #endif -->
		

        <!-- 无网络提示 -->
        <u-no-network z-index="1200" @retry="handleRetry"></u-no-network>

        <u-back-top
            :scroll-top="scrollTop"
            :top="1000"
            :customStyle="{
                backgroundColor: '#FFF',
                color: '#000',
                boxShadow: '0px 3px 6px rgba(0, 0, 0, 0.1)'
            }"
        ></u-back-top>
		
		<!-- 确认核销弹窗 -->
		<verify-code-dialog
		  ref="verifyCodeDialog"
		  :verify-code="verifyCode"
		  @refresh="reflesh"
		></verify-code-dialog>
    </view>
</template>

<script>
import { mapMutations, mapGetters, mapActions } from 'vuex'
import { getHome, getMenu, getBestList, getBambooRank, getSeckillTime, getSeckillGoods, getGoodsList, getCityByLocation, getCityArea, getCopywriting, getCopywritingLogin, getDefaultCity } from '@/api/store'
import { loadingType } from '@/utils/type'
import { loadingFun, menuJump, arraySlice, setTabbar, getRect, trottle, strToParams } from '@/utils/tools'
import { toLogin } from '@/utils/login'
import Cache from '@/utils/cache'
import { getConfig, userShare, getRegisterCoupon } from '@/api/app'
import { baseURL } from "@/config/app"
import area from '@/utils/area'
import { PROVINCE_CODE, CITY_CODE, REGION_CODE, VERIFY_CODE, CITY_DATA, CURRENT_LOCATION, DEFAULT_CITY, CITY_NAME } from "@/config/cachekey"


const app = getApp()
export default {
    data() {
        return {
			regionLists: [],
            scrollTop: 0,
            navSwiperH: 374,
            logo: '',
            navHeight: 0,
            currentSwiper: 0,
            page: 1,
            status: loadingType.LOADING,
			bambooRankPage: 1,
			bambooRankStatus: loadingType.LOADING,
            remainTime: '',
            navBg: 0,
            navList: [],
            news: [],
            seckill: {},
            seckillGoods: [],
            hotGoods: [],
            newGoods: [],
            activityArea: [],
            couponPopList: [],
            coupon: [],
            isDischarge: true,
            enable: true,
            showPrivacyPopup: false, //微信用户隐私协议
			tabActive: 0,
			tabList: [
				{
					name: '玉竹兑换',
					type: 1,
				},
				{
					name: '百亿补贴',
					type: 2,
				}
			],
			tabsConfig: {
				bgColor: 'tranpsarent',
				// 字体大小 rpx
				fontSize: 28,
				// 字体颜色
				color: '#333',
				// 激活字体颜色
				activeColor: '#366667',
				// 下划线宽度 rpx  注意：设置了此值 underLinePadding 失效
				underLineWidth: 46,
				// 下划线高度 rpx
				underLineHeight: 10,
				// 下划线颜色
				underLineColor: '#366667'
			},
			menuList: [
				{
					id: 1,
					name: '玉竹兑换',
					image: `${baseURL}/images/xcxweb/index/menu1.png`,
				},
				{
					id: 2,
					name: '苍蝇馆子',
					image: `${baseURL}/images/xcxweb/index/menu2.png`,
				},
				{
					id: 3,
					name: '景区门票',
					image: `${baseURL}/images/xcxweb/index/menu3.png`,
					path: ''
				},
				{
					id: 4,
					name: '电影专区',
					image: `${baseURL}/images/xcxweb/index/menu4.png`,
					path: ''
				},
				{
					id: 5,
					name: '优惠加油',
					image: `${baseURL}/images/xcxweb/index/menu5.png`,
					path: ''
				}
			],
			bambooRankList: [], // 玉竹排行榜
			seckilId: "",
			seckillTime: [], // 秒杀时间段
			seckillPage: 1, 
			seckillStatus: loadingType.LOADING,
			goodsList: [],
			keyword: "",
			goodsPage: 1,
			goodsStatus:  loadingType.LOADING,
			priceSort: "desc", // 销量排序:desc-降序；asc-升序
			saleSort: "desc",	// 价格排序:desc-降序；asc-升序
			// 当前位置信息
			currentLocation: {},
			// 城市信息
			cityData: {},
			// 区域信息
			// areaData: {}
			showShareBtn: false,
			shareInfo: Cache.get('shareInfo'),
			imgPrefix: baseURL,
			inviteOpenType: '',
			is_buy_card_case: '', // 是否购买卡包，0 否 1是
			copywritingObj: {},
			province_code: '', // 省code
			city_coding: '', // 城市code
			verifyCode: '', // 核销码
			regionFlag: false, // 区域
			hasMore: false, // 是否有更多，默认没有
			cityName: '', // 城市名字
        }
    },
    async onLoad(options) {
		console.log('首页options：---', options)
		if(options.scene){ // 有核销码
			   let verify_code = strToParams(decodeURIComponent(options.scene)).s;
			   console.log('verify_code', verify_code)
				if (verify_code) {
					 this.verifyCode = verify_code
					 this.$refs.verifyCodeDialog.open();
				}	
		}
	  	  
		
		// uni.removeStorageSync(PROVINCE_CODE)
		// uni.removeStorageSync(CITY_CODE)
		// uni.removeStorageSync(REGION_CODE)
		
        // #ifdef MP-WEIXIN
        if (wx.getPrivacySetting) {
            wx.getPrivacySetting({
                success: (res) => {
                    console.log(res, '------') // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
                    if (res.needAuthorization) {
                        // 需要弹出隐私协议
                        setTimeout(() => {
                            // uni.hideTabBar()
                        }, 100)
                        this.showPrivacyPopup = true
                    } else {
                        // uni.showTabBar()
                    }
                },
                fail: (err) => {
                    // uni.showTabBar()
                    console.log(err)
                }
            })
        } else {
            // uni.showTabBar()
        }

        // #endif

        this.headerAction = wx.createAnimation({
            delay: 0,
            duration: 100,
            timingFunction: 'ease-in-out'
        })
        this.onPageScroll = trottle(this.onPageScroll, 500, this)
        // setTabbar()
        this.navHeight = app.globalData.navHeight
        this.isDischarge = false
        console.log(this.appConfig)
		
		await this.getHomeFun()
		
		await this.getDefaultCityFun()
		
		
		
		this.initData()
		
		// console.log('this.currentLocation', this.currentLocation)
		// let { longitude, latitude } = this.currentLocation
		// console.log('longitude, latitude', longitude, latitude)
		
		this.$nextTick(() => {
		    this.regionLists = area
		})
    },
    async onShow() {
		// if(Cache.get(CITY_DATA)){ // 城市信息存在
		// 	this.cityData = Cache.get(CITY_DATA)
		// 	console.log('this.cityData', this.cityData)
		// 	let { city_code: city_coding } = this.cityData
		// 	this.city_coding = city_coding;
		// 	// Cache.set(CITY_CODE, city_coding)
		// }
		// if(Cache.get(CURRENT_LOCATION)){ // 当前位置信息存在
		// 	this.currentLocation = Cache.get(CURRENT_LOCATION)
		// 	this.user_lat = this.currentLocation.latitude
		// 	console.log('this.user_lat:', this.user_lat)
		// 	this.user_lng = this.currentLocation.longitude
		// 	console.log('user_lng:', this.user_lng)
		// }
		
		if(Cache.get(CURRENT_LOCATION)){ // 当前位置存在直接初始化活动列表
			console.log("有城市信息")
			this.initGoodsListFun()
		}else{ // 当前位置不存在重新获取位置后再请求活动列表
			console.log('没有城市信息')
			this.getCurrentCity()
		}
		
		console.log('Cache.get(CITY_NAME)', Cache.get(CITY_NAME))
		if(Cache.get(CITY_NAME)){ // 城市名字
			this.cityName = Cache.get(CITY_NAME)
			console.log('this.cityName', this.cityName)
			this.initGoodsListFun()
		}
		
		this.getCopywritingFun()
		
		console.log('this.inviteOpenType', this.inviteOpenType)
		if(this.isLogin){ // 登录状态时调用
			this.getUser().then((data) => {
						 console.log('getUser-data:', data)
						 if(data){
							 this.is_buy_card_case = data.is_buy_card_case;
							 console.log('是否购买卡包:', this.is_buy_card_case)
							 if(data.is_buy_card_case == 1){ // 购买了卡包才可以分享
								 this.inviteOpenType = 'share'
								 console.log('this.inviteOpenType', this.inviteOpenType)
							 }
						 }
			})
		}
		 
		 
        // this.$nextTick(function () {
        //     getRect('.index').then((res) => {
        //         if (res.top == 0) {
        //             this.navBg = 0
        //         }
        //     })
        // })

        // #ifdef H5
        this.enable = true
        // #endif
       
	
        // #ifdef MP
        wx.getUpdateManager().onUpdateReady(function () {
            wx.showModal({
                title: '更新提示',
                content: '新版本已经准备好，是否重启应用？',
                success(res) {
                    if (res.confirm) {
                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                        wx.getUpdateManager().applyUpdate()
                    }
                }
            })
        })
        // #endif
    },
    onHide() {
        // #ifdef H5
        this.enable = false
        // #endif
    },
    onReachBottom() {
	 //    this.getHomeFun()
		// this.getbambooRankFun()
		// this.getGoodsListFun()
		// this.getSeckillTimeFun()
		if(this.hasMore){
			this.getGoodsListFun()
		}
    },
    onPullDownRefresh() {
        this.getHomeFun()
		this.initData()
		this.initGoodsListFun()
    },
    onShareAppMessage() {
        console.log(this.inviteCode)
        const shareInfo = Cache.get('shareInfo')
		console.log('是否购买卡包:', this.is_buy_card_case)
		let path = 'pages/index/index'
		if(this.is_buy_card_case == 1){ // 购买了卡包
			path = 'pages/index/index?invite_code=' + this.inviteCode
		}
        return {
            title: shareInfo.mnp_share_title,
			path: path,
            imageUrl: shareInfo.mnp_share_image
        }
    },
    onPageScroll(e) {
       const top = uni.upx2px(100)
       const { scrollTop } = e
       if (!this.enable) return
       let percent = scrollTop / top
       this.navBg = percent > 1 ? 1 : percent
       this.scrollTop = scrollTop
    },
    destroyed() {
        this.isDischarge = true
    },
    methods: {
        ...mapMutations(['SETCONFIG']),
        ...mapActions(['getUser']),
        // 网络重试刷新网络请求（解决在ios中首次进入时需要授权蜂窝加载空白页面问题
        async handleRetry() {
            console.log('网络重试刷')
            try {
                const { code, data } = await getConfig()
                if (code == 1) {
                    this.SETCONFIG(data)
                    // setTabbar()
                }
            } catch (e) {
                // uni.showTabBar()
            }
            this.getShareInfo()
            this.getUser()
        },
		async getDefaultCityFun(){
			try {
			    const { code, data } = await getDefaultCity()
				console.log('默认城市data: ', data)
			    if (code == 1) {
			       Cache.set(DEFAULT_CITY, data)
			    }
			} catch (err) {
			   console.log('err', err)
			}
		},
		reflesh(){
			
		},
		getCopywritingFun(){
			if(!this.isLogin){ // 已登录
				getCopywriting().then((res) => {
					this.copywritingObj = res.data;
					console.log('this.copywritingObj', this.copywritingObj)
				})
			}else{ // 未登录
				getCopywritingLogin().then((res) => {
					this.copywritingObj = res.data;
					console.log('this.copywritingObj', this.copywritingObj)
				})
			}	
		},
		handleInvite(){
			console.log('是否购买卡包:', this.is_buy_card_case)
			console.log('this.inviteOpenType', this.inviteOpenType)
			
			if(!this.is_buy_card_case){ // 未购买卡包
				this.$toast({
					title: '请先前往购买卡包'
				})
			}else{
				// this.showShareBtn = true
			}
		},
		toDetails(id){
			uni.navigateTo({
				url: `/pages/goods_details/goods_details?id=${id}`
			})
		},
		initData(){
			this.initBambooRankFun()
			this.initSeckillTimeFun();
		},
		initBambooRankFun(){
			this.bambooRankPage = 1
			this.bambooRankList = []
			this.bambooRankStatus = loadingType.LOADING
			this.getbambooRankFun()
		},
		initSeckillTimeFun(){
			this.seckillPage = 1
			this.seckillGoods = []
			this.seckillStatus = loadingType.LOADING
			this.getSeckillTimeFun()
		},
		// 授权位置信息
		getCurrentCity(fn) {
			uni.getSetting({
				success: res => {
					if (res.authSetting && res.authSetting.hasOwnProperty("scope.userLocation")) {
						if (res.authSetting["scope.userLocation"]) {
							this.getLocation(fn)
						} else {
							uni.hideLoading()
							uni.showModal({
								title: '提示',
								content: '请重新授权获取您的地理位置，否则部分功能将无法使用',
								success: (res) => {
									if (res.confirm) {
										uni.openSetting({
											success: () => this.getLocation(fn)
										})
									} else {
										uni.showToast({
											title: '请授权获取您的地理位置，否则部分功能将无法使用',
											icon: 'none',
											duration: 2000
										})
									}
								},
								fail: (res) => {
									uni.showToast({
										title: '位置获取失败',
										icon: "none",
										duration: 2000
									})
								}
							})
						}
					} else {
						this.getLocation(fn)
					}
				}
			})
		},
		// 获取当前位置坐标
		getLocation (fn) {
		      let that = this
		      // 获取用户是否开启 授权获取当前的地理位置、速度的权限。
		      uni.getSetting({
		        success (res) {
		          console.log(res)
		
		          // 如果没有授权
		          if (!res.authSetting['scope.userLocation']) {
		            // 则拉起授权窗口
		            uni.authorize({
		              scope: 'scope.userLocation',
		              success () {
		                //点击允许后--就一直会进入成功授权的回调 就可以使用获取的方法了
		                uni.getLocation({
		                  type: 'wgs84',
						  geocode: true,//设置该参数为true可直接获取经纬度及城市信息
		                  success: function (res) {
							console.log('允许授权res', res)
		                    that.x = res.longitude
		                    that.y = res.latitude
		                    console.log(res)
		                    console.log('当前位置的经度：' + res.longitude)
		                    console.log('当前位置的纬度：' + res.latitude)
							that.currentLocation = res
							
							Cache.set(CURRENT_LOCATION, res)
							
							this.user_lat = res.latitude
							console.log('this.user_lat:', this.user_lat)
							this.user_lng = res.latitude
							console.log('user_lng:', this.user_lng)
							
							that.getCurCity()
							
		                    // uni.showToast({
		                    //   title: '当前位置的经纬度：' + res.longitude + ',' + res.latitude,
		                    //   icon: 'success',
		                    //   mask: true
		                    // })
		                  }, fail (error) {
		                    console.log('失败', error)
							uni.showToast({
								title: error.errMsg,
								icon: 'error',
								mask: true
							})
		                  }
		                })
		              },
		              fail (error) {
		                //点击了拒绝授权后--就一直会进入失败回调函数--此时就可以在这里重新拉起授权窗口
		                console.log('拒绝授权', error)
		                uni.showModal({
		                  title: '提示',
		                  content: '若点击不授权，将无法使用位置功能',
		                  cancelText: '不授权',
		                  cancelColor: '#999',
		                  confirmText: '授权',
		                  confirmColor: '#f94218',
		                  success (res) {
		                    console.log(res)
		                    if (res.confirm) {
		                      // 选择弹框内授权
		                      uni.openSetting({
		                        success (res) {
		                          console.log(res.authSetting)
		                        }
		                      })
		                    } else if (res.cancel) {
		                      // 选择弹框内 不授权
		                      console.log('用户点击不授权')
							  that.initGoodsListFun()
		                    }
		                  }
		                })
		              }
		            })
		          } else {
		            // 有权限则直接获取
		            uni.getLocation({
		              type: 'wgs84',
					  geocode: true,//设置该参数为true可直接获取经纬度及城市信息
		              success: function (res) {
		                that.x = res.longitude
		                that.y = res.latitude
		                console.log(res)
		                console.log('当前位置的经度：' + res.longitude)
		                console.log('当前位置的纬度：' + res.latitude)
						console.log('允许授权res', res)
						that.currentLocation = res
						that.getCurCity()
		                // uni.showToast({
		                //   title: '当前位置的经纬度：' + res.longitude + ',' + res.latitude,
		                //   icon: 'success',
		                //   mask: true
		                // })
		              }, fail (error) {
		                uni.showToast({
		                  title: '请勿频繁调用！',
		                  icon: 'none',
		                })
		                console.log('失败', error)
		              }
		            })
		          }
		        }
		      })
		},
		async getCurCity(){
			console.log('this.currentLocation', this.currentLocation)
			let { longitude, latitude } = this.currentLocation
			let params = {
				lng: longitude,
				lat: latitude
			}
			let res = await getCityByLocation(params)
			// console.log('getCurCity--res', res)
			console.log('根据当前经纬度返回的城市信息：', res)
			this.cityData = res.data;
			console.log('this.cityData', this.cityData)
			Cache.set(CITY_DATA, res.data)
			let {city_code: city_coding, city } = this.cityData
			// this.city_coding = city_coding;
			console.log('city_coding:', city_coding)
			console.log('city', city)
			console.log('get-cur-city')
			Cache.set(CITY_CODE, city_coding)
			Cache.set(CITY_NAME, city)
			this.cityName = city
			this.initGoodsListFun()
		},
		handleMenu(item, index){
			// if(item.path){
			// 	if (!this.isLogin) return toLogin()
			// 	uni.navigateTo({
			// 		url: item.path
			// 	})
			// }else 
			if (!this.isLogin) return toLogin()
			
			let { longitude:user_lng = '', latitude:user_lat = '' } = this.currentLocation
			let { province_code = '', city_coding = '' } = this
			console.log('点击菜单的params：', user_lat, user_lng, province_code, city_coding)
			
			if(item.id == 1){ // 玉竹兑换
				uni.navigateTo({
					url: `/bundle/pages/bamboo_search/bamboo_search`
				})
			}else if(item.id == 2){ // 苍蝇馆子
				uni.navigateTo({
					url: `/bundle/pages/fly_restaurant/fly_restaurant`
				})
			}else{
				this.$toast({
					title: '敬请期待！'
				})
			}   
		},
		onTabChange(active){
			console.log('active', active)
			this.tabActive = active;
			this.initGoodsListFun()
		},
		handleCityChange(){
			console.log('切换城市')
			uni.navigateTo({
				url: `/bundle/pages/select_city/select_city`
			})
		},
		initGoodsListFun(){
			this.goodsStatus = loadingType.LOADING
			this.goodsPage = 1
			this.goodsList = []
			this.getGoodsListFun()
		},
        async getShareInfo() {
            const { code, data } = await userShare()
            if (code == 1) {
                Cache.set('shareInfo', data)
            }
        },
        async getHomeFun() {
            const { code, data } = await getHome()
            uni.stopPullDownRefresh()
            if (code == 1) {
                const { coupon, news, seckill, host_goods, shop_logo, new_goods, activity_area } =
                    data
                this.remainTime = Math.abs(seckill.end_time - Date.parse(new Date()) / 1000)
                this.logo = shop_logo
                this.news = news || []
                this.seckillGoods = seckill.goods
                this.seckill = seckill
                this.coupon = coupon 
                this.activityArea = activity_area
            }
        },
		async getGoodsListFun() {
			let {
				goodsPage,
				goodsList,
				keyword,
				priceSort,
				saleSort,
				goodsStatus,
				navType
			} = this;
			console.log('goodsStatus', goodsStatus)
			console.log('loadingType.FINISHED', loadingType.FINISHED)
			if (goodsStatus == loadingType.FINISHED) return;
			// let { longitude:user_lng, latitude:user_lat } = this.currentLocation
			
			
			console.log('this.city_coding', this.city_coding)
			let { longitude, latitude } = Cache.get(CURRENT_LOCATION) // 当前位置
			let defaultCity = Cache.get(DEFAULT_CITY); // 默认城市，成都
			console.log('defaultCity', defaultCity)
			
			const params = {
				keyword,
				sales_sum: saleSort,
				price: priceSort,
				page_no: goodsPage,
				type: navType, // type: 商品类型默认2; 1:玉竹兑换商品 2：普通商品（默认）
				user_lat: latitude || defaultCity.lat, // 没有获取到经纬度就取默认的经纬度
				user_lng: longitude || defaultCity.lon, // 没有获取到经纬度就取默认的经纬度
				city_coding:  Cache.get(CITY_CODE) || ''
			}
			console.log('商品列表参数-params：', params)
			
			const data = await loadingFun(getGoodsList, goodsPage, goodsList, goodsStatus, params)
			console.log('goodsList-data', data)
			if (!data) return
			this.goodsPage = data.page
			this.goodsList = data.dataList
			console.log('this.goodsList', this.goodsList)
			this.goodsStatus = data.status
			this.hasMore = data.hasMore
		},
		// 玉竹兑换排行榜
		async getbambooRankFun() {
		    let { bambooRankPage, bambooRankList, bambooRankStatus } = this
		    const data = await loadingFun(getBambooRank, bambooRankPage, bambooRankList, bambooRankStatus)
		    if (!data) return
		    this.bambooRankPage = data.page
		    this.bambooRankList = data.dataList
			console.log('this.bambooRankList', this.bambooRankList)
		    this.bambooRankStatus = data.status
		},
		// 获取秒杀时间段
		getSeckillTimeFun() {
		  getSeckillTime().then(res => {
		    if (res.code == 1) {
		      if (!res.data.length && res.data.length <= 0) {
		        return;
		      }
		
		      let index = res.data.findIndex(item => item.status == 1);
		
		      if (index == -1) {
		        index = res.data.findIndex(item => item.status == 0);
		      }
		
		      if (index == -1) {
		        index = 0;
		      }
		
		     
		
		      this.seckillTime = res.data;
		      this.seckilId = res.data[index].id
		      
		      this.getSeckillGoodsFun(res.data[index].id);
		    }
		  });
		},
		// 获取秒杀时间段商品
		getSeckillGoodsFun(id) {
		  let {
		    seckillPage,
		    seckillGoods
		  } = this;
		
		  loadingFun(getSeckillGoods, seckillPage, seckillGoods, this.seckillStatus, {id: id}).then(res => {
		      if(res) {
		          this.seckillPage = res.page;
		          this.seckillGoods = res.dataList
				  console.log('this.seckillGoods', this.seckillGoods)
		          this.seckillStatus = res.status
		      }
		  })
		},
        async tapMenu(item) {
            if (!this.isLogin) return toLogin()
            menuJump(item)
        },
        goPage(url) {
            if (!this.isLogin) return toLogin()
            uni.navigateTo({
                url
            })
        },
    },
    computed: {
        ...mapGetters(['inviteCode', 'appConfig', 'userInfo']),
		navBackground(){
			let resultBg = {}
			if(this.navBg > 0.5){
				resultBg = {
					backgroundImage:  `linear-gradient(90deg,  #569496 0%, #366667 100%)`
				}
			}
			return resultBg;
		},
        showLogo() {
            return this.seting.logo
        },
        seting() {
            const { index_setting } = this.appConfig
            return index_setting
        },
		navType() {
			return this.tabList[this.tabActive].type
		}
    }
}
</script>

<style lang="scss" scoped>
.u-nav-slot{
	font-weight: 500;
	font-size: 32rpx;
	color: #FFFFFF;
	.location-img{
		width: 30rpx;
		height: 36rpx;
		margin-right: 18rpx;
	}
}

.search-wrapper{
	margin: 28rpx 22rpx 0 0;
	.search-box{
		width: 88rpx;
		height: 60rpx;
		line-height: 64rpx;
		text-align: center;
		background: rgba(255,255,255,0.31);
		border-radius: 332rpx 332rpx 332rpx 332rpx;
		border: 2rpx solid rgba(255,255,255,0.12);
		image{
			width: 32rpx;
			height: 32rpx;
		}
	}
}

.home-bg {
    background: url(#{$img_prefix}/images/xcxweb/index/index_bg.png) no-repeat;
    background-size: 100% auto;
}
.index {
    .live-play {
        position: fixed;
        z-index: 999;
        bottom: 200rpx;
        right: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 80rpx;
        height: 80rpx;
        border: $-solid-border;
        border-radius: 50%;
        font-size: 32rpx;
        background-color: #ffffff;

        &__icon {
            animation: scale 0.5s infinite;
        }

        @keyframes scale {
            from {
                top: 0px;
                transform: scale(1);
            }
            to {
                transform: scale(1.2);
            }
        }
    }

    background-size: 100% auto;

    .logo-wrap {
        position: absolute;

        .logo {
            width: auto;
            height: 52rpx;
        }
    }

    .header {
        .navigation-bar {
            padding-top: var(--status-bar-height);
            box-sizing: border-box;
        }
    }

    .contain {
        .main {
            position: relative;
            z-index: 9;
            padding: 0 20rpx;

            .nav {
                position: relative;
                border-radius: 14rpx;

                .nav-item {
                    width: 20%;
                    margin-top: 30rpx;

                    .nav-icon {
                        width: 82rpx;
                        height: 82rpx;
                        margin-bottom: 15rpx;
                    }
                }

                .dots {
                    position: absolute;
                    left: 50%;
                    transform: translateX(-50%);
                    bottom: 20rpx;
                    display: flex;

                    .dot {
                        width: 10rpx;
                        height: 6rpx;
                        border-radius: 6rpx;
                        margin-right: 10rpx;
                        background-color: rgba(255, 44, 60, 0.4);

                        &.active {
                            width: 20rpx;
                            background-color: $-color-primary;
                        }
                    }
                }
            }
			
			.menu-box{
				margin-top: 310rpx;
				background: url(#{$img_prefix}/images/xcxweb/index/men_box_bg.png) no-repeat;
				height: 252rpx;
				background-size: 100% 100%;
				padding: 24rpx 24rpx;
				box-sizing: border-box;
				.menu-item{
					font-weight: 500;
					font-size: 24rpx;
					color: #FFFFFF;
					line-height: 34rpx;
					margin-top: 28rpx;
					image{
						width: 92rpx;
						height: 92rpx;
						margin-bottom: 20rpx;
					}
				}
			}
			
			.invite-box{
				width: 710rpx;
				height: 208rpx;
				margin: 14rpx auto 40rpx;
				box-sizing: border-box;
				position: relative;
				image{
					display: block;
					width: 710rpx;
					height: 208rpx;
				}
				.invite-txt-box{
					.txt1{
						position: absolute;
						left: 208rpx;
						top: 46rpx;
						font-size: 36rpx;
						color: #687440;
						font-weight: bold;
						letter-spacing: 2rpx;
						text{
							color: #EBCB2B;
						}
					}
					.txt2{
						position: absolute;
						left: 194rpx;
						top: 78rpx;
						font-size: 58rpx;
						color: #456E69;
						font-weight: 1000;
						letter-spacing: 6rpx;
						-webkit-transform: skewX(-4deg);
						transform: skewX(-4deg);
						text{
							color: #EBCB2B;
						}
					}
				}
			}

			.seckill-box{
				display: flex;
				justify-content: space-between;
				align-items: stretch;
				.left{
					width: 350rpx;
					// border-radius: 10rpx;
					padding: 20rpx 14rpx 12rpx;
					background: url(#{$img_prefix}/images/xcxweb/index/bamboo_rank_bg.png) no-repeat;
					background-size: 100% 100%;
					.hd{
						margin-bottom: 16rpx;
						font-size: 30rpx;
						color: #366667;
						line-height: 36rpx;
						font-weight: bold;
						image{
							width: 15rpx;
							height: 22rpx;
						}
					}
					.bd{
						.goods-item{
							position: relative;
							width: 324rpx;
							height: 222rpx;
							margin-bottom: 14rpx;
							border-radius: 16rpx;
							&:last-child{
								margin-bottom: 0;
							}
							.goods-img{
								width: 100%;
								height: 100%;
								border-radius: 16rpx;
							}
							.rank-img{
								position: absolute;
								left: 0;
								top: 0;
								width: 126rpx;
								height: 38rpx;
							}
							.exchange-btn{
								position: absolute;
								right: 10rpx;
								top: 12rpx;
								padding: 8rpx 14rpx;
								background: rgba(255,194,51,0.78);
								border-radius: 16rpx 16rpx 16rpx 16rpx;
								color: #FFFFFF;
								line-height: 28rpx;
							}
							.desc-box{
								width: 100%;
								position: absolute;
								left: 0;
								bottom: 0;
								padding: 16rpx 26rpx;
								background: rgba(0,0,0,0.72);
								border-radius: 0rpx 0rpx 16rpx 16rpx;
								font-size: 20rpx;
								color: #FFFFFF;
							}
						}
					}
				}
				.right{
					width: 350rpx;
					// border-radius: 10rpx;
					padding: 20rpx 14rpx 12rpx;
					background: url(#{$img_prefix}/images/xcxweb/index/seckill_bg.png) no-repeat;
					background-size: 100% 100%;
					.hd{
						font-weight: 400;
						font-size: 28rpx;
						line-height: 36rpx;
						font-weight: bold;
						margin-bottom: 16rpx;
						.countdown-box{
							.item{
								padding: 6rpx;
								background: #FF7272;
								border-radius: 6rpx;
								font-weight: 700;
								font-size: 20rpx;
								color: #FFFFFF;
							}
							text{
								margin: 0 4rpx;
							}
						}
					}
					.bd{
						.goods-img{
							width: 310rpx;
							height: 316rpx;
							border-radius: 16rpx;
						}
						.info-box{
							margin: 12rpx 0 8rpx;
							.title{
								font-weight: 400;
								font-size: 28rpx;
								color: #333333;
								line-height: 40rpx;
								max-width: 250rpx;
								overflow: hidden;
								white-space: nowrap;
								text-overflow: ellipsis;
							}
							.able-btn{
								width: 98rpx;
								height: 34rpx;
								line-height: 34rpx;
								text-align: center;
								background: linear-gradient( 270deg, #FFFAD9 0%, #FFFB18 100%);
								border-radius: 8rpx 8rpx 8rpx 8rpx;
								font-weight: 500;
								font-size: 24rpx;
								color: #FF7F08;
								line-height: 34rpx;
							}
						}
						.price-box{
							padding: 8rpx 10rpx;
							background: linear-gradient( 270deg, #D64334 0%, #ED7432 100%);
							border-radius: 8rpx 8rpx 8rpx 8rpx;
							.price{
								font-size: 24rpx;
								color: #FFFFFF;
								line-height: 28rpx;
								margin-right: 18rpx;
							}
							.unit-box{
								flex: 1;
								padding: 8rpx 10rpx;
								text-align: center;
								background: #FFFFFF;
								border-radius: 8rpx 8rpx 8rpx 8rpx;
								font-weight: 500;
								font-size: 28rpx;
								line-height: 40rpx;
								color: #EB5A4B;
							}
						}
					}
				}
			}
			
			.show-goods-box{
				margin-top: 30rpx;
				.show-goods-list{
					margin-top: 40rpx;
					.show-goods-item{
						.imgs-box{
							position: relative;
							width: 710rpx;
							height: 296rpx;
							border-radius: 12rpx;
							image{
								width: 100%;
								height: 100%;
								border-radius: 12rpx;
							}
							.distance-box{
								position: absolute;
								left: 12rpx;
								bottom: 10rpx;
								padding: 12rpx 16rpx;
								background: rgba(0,0,0,0.58);
								border-radius: 8rpx 8rpx 8rpx 8rpx;
								font-size: 24rpx;
								color: #FFFFFF;
							}
						}
						.content-box{
							position: relative;
							padding: 16rpx 20rpx;
							background: #FFF;
							.title{
								margin: 16rpx 0 8rpx;
								font-weight: 500;
								font-size: 30rpx;
								color: #333333;
								line-height: 40rpx;
							}
							.intro{
								font-size: 24rpx;
								color: #999999;
								line-height: 36rpx;
							}
							.num-box{
								margin-top: 10rpx;
								font-size: 20rpx;
								color: #999999;
								line-height: 28rpx;
								.price-box{
									font-weight: 700;
									font-size: 48rpx;
									color: #FF7125;
									line-height: 32rpx;
									.unit{
										margin-left: 8rpx;
										font-size: 28rpx;
									}
								}
								.subsidy-box{
									margin-left: 24rpx;
									padding: 8rpx 16rpx;
									font-size: 20rpx;
									color: #CC760C;
									line-height: 28rpx;
									background: rgba(255,197,82,0.3);
									border-radius: 8rpx 8rpx 8rpx 8rpx;
								}
							}
							.exchange-box{
								position: absolute;
								right: 20rpx;
								bottom: 12rpx;
								width: 114rpx;
								height: 92rpx;
								text-align: center;
								background: url(#{$img_prefix}/images/xcxweb/index/exchange_bg.png) no-repeat;
								background-size: 100% 100%;
								color: #FFF;
								font-size: 24rpx;
								padding: 18rpx 0 0 0;
								line-height: 30rpx;
							}
							.gain-box{
								position: absolute;
								right: 20rpx;
								bottom: 12rpx;
								width: 136rpx;
								height: 54rpx;
								text-align: center;
								background: url(#{$img_prefix}/images/xcxweb/index/gain_bg.png) no-repeat;
								background-size: 100% 100%;
								color: #FFF;
								font-size: 24rpx;
								padding: 22rpx 0 0 16rpx;
								line-height: 28rpx;
							}
						}
					}
				}
			}
			
            .information {
                height: 76rpx;
                box-shadow: 0px 0px 14px rgba(0, 0, 0, 0.06);
                padding: 0 20rpx;
                box-sizing: border-box;
                border-radius: 14rpx;

                .news {
                    position: relative;

                    .shade {
                        position: absolute;
                        width: 100%;
                        height: 100%;
                        z-index: 100;
                    }
                }

                .icon-toutiao {
                    width: 114rpx;
                    height: 34rpx;
                }

                .gap-line {
                    height: 28rpx;
                    width: 1px;
                    background-color: #dcdddc;
                    margin: 0 30rpx;
                }
            }

            .special-area {
                .item {
                    width: 300rpx;
                    border-radius: 20rpx;
                    display: inline-block;
                    overflow: hidden;
                    margin-right: 20rpx;

                    .title {
                        padding: 10rpx 0;
                    }

                    .desc {
                        background-color: #fee9eb;
                        padding: 6rpx 20rpx;
                        border-radius: 60rpx;
                        max-width: 260rpx;
                    }
                }
            }

            .activity-header {
                height: 90rpx;
                padding: 0 20rpx;
            }

            .seckill {
                .dec {
                    background-color: #fffbdb;
                    width: 150rpx;
                }
            }

            .hot,
            .new-goods {
                .title-image {
                    width: 144rpx;
                    height: 55rpx;
                }
            }
        }

        .goods {
            .goods-title {
                height: 100rpx;

                .line {
                    width: 58rpx;
                    height: 1px;
                    background-color: #ccc;
                    margin: 0 22rpx;
                }

                .icon {
                    width: 38rpx;
                    height: 38rpx;
                }
            }
        }
    }
}
</style>
